package com.adulcimer.services;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.adulcimer.core.tools.DemonExceptionMessage;
import com.adulcimer.models.entity.domain.Posts;
import com.adulcimer.models.dto.DemonIdsStringDto;
import com.adulcimer.models.dto.PostsSaveDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.adulcimer.models.entity.service.PostsService;
import com.adulcimer.core.tools.DemonPagingModel;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Simon
 * @create 2025/2/6
 * @Description
 **/

@Service
public class LocalPostsService extends BaseService {
    @Resource
    private PostsService postsService;

    public DemonPagingModel<List<Posts>> list(Integer pageNumber, Integer pageSize, Integer status, String q) {
        Page<Posts> page = new Page<>(pageNumber, pageSize);
        postsService.lambdaQuery().eq(Posts::getStatus, status)
                .like(StrUtil.isNotEmpty(q), Posts::getTitle, q)
                .page(page);
        return new DemonPagingModel<>(pageNumber, pageSize, page.getTotal(), page.getRecords());
    }

    public void save(PostsSaveDto postsSaveDto){
        if(StrUtil.isEmpty(postsSaveDto.getTitle())){
            throw new DemonExceptionMessage("标题不能为空");
        }
        Posts posts = new Posts();
        BeanUtil.copyProperties(postsSaveDto, posts);
        posts.setCreatedBy(getUserId());
        postsService.saveOrUpdate(posts);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(DemonIdsStringDto ids){
        postsService.removeByIds(ids.getIds());
    }
}
